package com.snail.service.impl;

import cn.hutool.core.lang.TypeReference;
import com.snail.apis.ProductApi;
import com.snail.exception.BizException;
import com.snail.exception.BusinessException;
import com.snail.mapper.BizCartItemMapper;
import com.snail.mapper.BizCartMapper;
import com.snail.model.dto.cart.AddCartRequestDto;
import com.snail.model.pojo.cart.BizCart;
import com.snail.model.pojo.cart.BizCartItem;
import com.snail.model.pojo.mall.BizProduct;
import com.snail.model.pojo.mall.BizProductSku;
import com.snail.model.vo.cart.BizProductSkuVo;
import com.snail.model.vo.user.LoginUser;
import com.snail.result.Result;
import com.snail.service.BizCartService;

import com.snail.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class BizCartServiceImpl implements BizCartService {
    @Autowired
    private BizCartMapper bizCartMapper;

    @Autowired
    private BizCartService bizCartService;
    @Autowired
    private BizCartItemMapper cartItemMapper;


    //添加商品到购物车
    @Override
    public void addToCart(AddCartRequestDto addCartRequestDto) {
        // 1. 校验商品是否存在 + 库存是否充足
//        BizProduct product = bizCartMapper.selectById(addCartRequestDto.getProductId());
        BizProductSku product = bizCartMapper.selectByProductId(addCartRequestDto.getProductId(), addCartRequestDto.getSpecs());

        BizProductSkuVo skuWithSeller = bizCartMapper.getSkuWithSeller(addCartRequestDto.getProductId());
        System.out.println(skuWithSeller);
        BizProductSkuVo skuWithSellerAndProductName = bizCartMapper.getSkuWithSellerAndProductName(addCartRequestDto.getProductId(), addCartRequestDto.getSpecs());
//        Result result = productApi.selectById(addCartRequestDto.getProductId());
//        if (!Result.isSuccess(result) || result.getData() == null) {
//            throw new BusinessException(400, "查询商品失败：" + result.getMsg());
//        }
//        BizProduct product = (BizProduct) result.getData();


//        if (product == null || product.getDeleted() == 1) {
//            throw new BizException(400, "商品不存在或已下架");
//        }
        if (product.getRealStock() < addCartRequestDto.getQuantity()) {
            throw new BusinessException(400, "库存不足，当前库存：" + product.getRealStock());
        }
        //获取当前登录用户的方法：
        LoginUser currentUser = SecurityUtils.getCurrentUser();
        Long userId = currentUser.getUserId();
        addCartRequestDto.setUserId(userId);

        // 获取商品价格（核心：从商品信息中提取价格）
        Double productPrice = product.getRealPrice();

        // 2. 获取或创建用户的购物车（1用户→1购物车）
        BizCart cart = bizCartService.getOrCreateCart(addCartRequestDto.getUserId());

        // 3. 检查商品是否已在购物车中
        BizCartItem existingItem = cartItemMapper.selectByCartIdAndProductId(
                cart.getCartId(),
                addCartRequestDto.getProductId()
        );

        if (existingItem != null) {
            // 3.1 商品已存在 → 更新数量
            int newQuantity = existingItem.getQuantity() + addCartRequestDto.getQuantity();
            // 二次校验库存（防止并发超卖）
            if (newQuantity > product.getRealStock()) {
                System.out.println("库存不足，当前库存：" + product.getRealStock());
            }
            existingItem.setQuantity(newQuantity);
            // 可选：如果商品价格可能变动，这里同步更新最新价格
            existingItem.setPrice(productPrice);
            cartItemMapper.updateById(existingItem);
        } else {
            // 3.2 商品不存在 → 新增商品项
            BizCartItem newItem = new BizCartItem();
            newItem.setCartId(cart.getCartId());
            newItem.setProductId(addCartRequestDto.getProductId());
            newItem.setSellerUserId(skuWithSeller.getSellerUserId()); // 从商品获取卖家ID
            newItem.setQuantity(addCartRequestDto.getQuantity());
            newItem.setPrice(productPrice);
            newItem.setSpecs(addCartRequestDto.getSpecs());
            newItem.setSelected(true); // 默认选中
            newItem.setProductName(skuWithSellerAndProductName.getProductName());
//            cartItemMapper.insert(newItem);
            cartItemMapper.insertCartItem(newItem);
        }
    }

    //通过用户id查询购物车是否存在
    @Override
    public BizCart getOrCreateCart(Long userId) {
        BizCart bizCart = bizCartMapper.selectByUserId(userId);
        if (bizCart != null) {
            return bizCart;
        }
        // 尝试创建购物车，处理并发重复插入
        try {
            BizCart newCart = new BizCart();
            newCart.setUserId(userId);
            newCart.setDeleted(false);
            bizCartMapper.insert(newCart);
            return newCart;
        } catch (DuplicateKeyException e) {
            // 并发插入冲突，重新查询
            return bizCartMapper.selectByUserId(userId);
        }
    }

    @Override
    public BizProduct selectById(Integer productId) {
        BizProduct bizProduct = bizCartMapper.selectById(productId);
        return bizProduct;
    }
}
